import { ValidationPipe } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { NestExpressApplication } from "@nestjs/platform-express";
import { BaseExceptionFilter } from "@/common/filters/base-exception.filter";
import { AppModule } from "./app.module";
import { DatabaseExceptionFilter } from "./common/filters/database-exception.filter";

// 解决 JSON.stringify(BigInt) 报错问题, 避免数据库使用 bigint 类型无法解析
(BigInt.prototype as any).toJSON = function () {
    return this.toString();
};

async function bootstrap() {
    const app = await NestFactory.create<NestExpressApplication>(AppModule);

    /**
     * 查询参数解析
     * 参考: https://nest.nodejs.cn/controllers#%E6%9F%A5%E8%AF%A2%E5%8F%82%E6%95%B0
     */
    app.set("query parser", "extended");

    /*
     * 全局异常过滤器
     * 参考: https://nest.nodejs.cn/exception-filters#%E5%BC%82%E5%B8%B8%E8%BF%87%E6%BB%A4%E5%99%A8
     */
    app.useGlobalFilters(new BaseExceptionFilter(), new DatabaseExceptionFilter());

    /*
     * 全局管道, 用于请求时使用 class-validator 的类校验( @Body 和 @Query 都可以)
     * 参考: https://nest.nodejs.cn/pipes#%E5%85%A8%E5%B1%80%E4%BD%9C%E7%94%A8%E5%9F%9F%E7%AE%A1%E9%81%93
     * 注意默认情况下，ValidationPipe 不验证使用自定义装饰器注释的参数
     * 参考: https://nest.nodejs.cn/custom-decorators#%E4%BD%BF%E7%94%A8%E7%AE%A1%E9%81%93
     */
    app.useGlobalPipes(new ValidationPipe({ whitelist: true }));

    await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
